import {
  Card,
  Table,
  Button,
  Col,
  Divider,
  Icon,
  Input,
  Modal,
  Row,
  message,
  Tooltip
} from 'antd';
import React, { Component, Fragment, createRef } from 'react';

import { Dispatch } from 'redux';
import { FormComponentProps } from 'antd/es/form';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { connect } from 'dva';
import { ProductModelState } from '@/models/product';
import { TypeModelState } from '@/models/type';
import { CompanyModelState } from '@/models/company';
import AddModal from './components/addModal';

import styles from './style.less';

interface TableListProps extends FormComponentProps {
  dispatch: Dispatch<any>;
  loading: boolean;
  product: ProductModelState;
  type: TypeModelState;
  company: CompanyModelState;
}

interface TableListState {
  offset: number;
  limit: number;
  modelVisible: boolean;
  selectedRows: string[];
}

interface TableListItem {
  pid: number;
}

/* eslint react/no-multi-comp:0 */
@connect(
  ({
    product,
    type,
    company,
    loading,
  }: {
    product: ProductModelState;
    type: TypeModelState,
    company: CompanyModelState,
    loading: {
      models: {
        [key: string]: boolean;
      };
    };
  }) => ({
    product,
    type,
    company,
    loading: loading.models.product,
  }),
)
class TableList extends Component<TableListProps, TableListState> {
  state: TableListState = {
    offset: 1,
    limit: 10,
    selectedRows: [],
    modelVisible: false,
  };

  searchInput = createRef<Input>();

  componentDidMount() {
    const { dispatch } = this.props;
    this.fetchProduct();

    dispatch({
      type: 'type/fetch',
    });

    dispatch({
      type: 'company/fetch',
    });
  }

  fetchProduct = () => {
    const { offset, limit } = this.state;
    const { dispatch } = this.props;
    dispatch({
      type: 'product/fetch',
      payload: {
        offset,
        limit
      }
    });
  }

  handleSelectRows = (rows: string[]) => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleSearch = () => {
    const { value } = this.searchInput.current!.state;
    const { dispatch } = this.props;

    if (value) {
      dispatch({
        type: 'product/fetch',
        payload: {
          offset: 1,
          limit: 10,
          productName: value
        }
      });
    } else {
      message.error('请输入产品名称');
    }
  };

  handleAdd = (values: any) => {
    const { dispatch } = this.props;
    const formData = new FormData();
    for (let i in values) {
      if (i === 'file') {
        formData.append(i, values[i].file);
      } else {
        formData.append(i, values[i]);
      }
    }

    dispatch({
      type: 'product/add',
      payload: formData,
      callback: () => {
        this.fetchProduct();
        this.handleModalVisible();
        message.success('添加成功');
      }
    });
  };

  handleUpdate = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'product/update',
      payload: {

      },
    });

    message.success('配置成功');
  };

  handleDelete = (productId: number) => {
    const { dispatch } = this.props;
    Modal.confirm({
      title: 'Confirm delete ？',
      onOk: () => {
        dispatch({
          type: 'product/delete',
          payload: {
            productId
          },
        });

        message.success('删除成功');
      }
    })
  }

  handleModalVisible = (flag?: boolean) => {
    this.setState({
      modelVisible: !!flag
    })
  }

  render() {
    const {
      product,
      type,
      company,
      loading
    } = this.props;
    const {
      modelVisible
    } = this.state;
    return (
      <PageHeaderWrapper>
        <Card bordered={false}>
          <Row
            gutter={{ md: 8, lg: 24, xl: 48 }}
            style={{ marginBottom: 24 }}>
            <Col
              md={8} sm={24}>
              <Input
                placeholder="请输入产品名称"
                ref={this.searchInput} />
            </Col>
            <Col
              md={8} sm={24}>
              <Button
                type="primary"
                onClick={this.handleSearch}>查询</Button>
            </Col>
            <Col
              style={{ float: 'right' }}>
              <Button
                type="primary"
                onClick={() => this.handleModalVisible(true)}>新增</Button>
            </Col>
          </Row>
          <div className={styles.tableList}>
            <Table
              rowKey='pid'
              columns={[{
                title: '产品名称',
                dataIndex: 'pname',
              }, {
                title: '产品描述',
                dataIndex: 'pdesc',
                width: 300,
                render: val => <Tooltip title={val}>{val}</Tooltip>,
              }, {
                title: '创建时间',
                dataIndex: 'createdAt',
              }, {
                title: '更新时间',
                dataIndex: 'updatedAt',
              }, {
                title: '操作',
                render: (text, record: TableListItem) => (
                  <Fragment>
                    <a onClick={() => { }}><Icon type="edit" /> 编辑</a>
                    <Divider type="vertical" />
                    <a onClick={() => this.handleDelete(record.pid)}><Icon type="delete" /> 删除</a>
                  </Fragment>
                )
              }]}
              loading={loading}
              dataSource={product.data.rows} />
          </div>
        </Card>
        <AddModal
          modelVisible={modelVisible}
          handleModalVisible={this.handleModalVisible}
          type={type.data}
          company={company.data}
          handleAdd={this.handleAdd} />
      </PageHeaderWrapper>
    );
  }
}

export default TableList;
